package no.ntnu.fp.messages.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import no.ntnu.fp.messages.Message;
import no.ntnu.fp.messages.MessageCode;
import no.ntnu.fp.model.Employee;
import no.ntnu.fp.utils.XmlParser;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class EmployeesFetchedMessage implements Message {

	private final List<Employee> employees;
	
	public EmployeesFetchedMessage() {
		this(Collections.<Employee>emptyList());
	}
	
	public EmployeesFetchedMessage(List<Employee> employees) {
		this.employees = new ArrayList<Employee>(employees);
	}

	public List<Employee> getEmployees() {
		return new ArrayList<Employee>(employees);
	}

	@Override
	public MessageCode getMessageCode() {
		return MessageCode.EMPLOYEES_FETCHED_MESSAGE;
	}

	@Override
	public Message fromXmlString(String xml) {
		Document doc = XmlParser.parseXmlString(xml);
		
		NodeList employeeNodes = doc.getElementsByTagName("employees");
		NodeList employeeList = ((Element)employeeNodes.item(0)).getChildNodes();
		
		List<Employee> employees = new ArrayList<Employee>();
		for(int i = 0; i < employeeList.getLength(); i++){
			employees.add(new Employee((Element)(employeeList.item(i))));
		}
		
		return new EmployeesFetchedMessage(employees);
	}

	@Override
	public String toString() {
		Document doc = XmlParser.getThreadLocalDocumentBuilder().newDocument();
		Element root = doc.createElement("message");
		
		Element employeesElement = doc.createElement("employees");
		
		for(Employee emp : this.employees){
			employeesElement.appendChild(emp.toXml(doc));
		}
		
		root.appendChild(employeesElement);
		
		return getMessageCode() + XmlParser.convertXmlToString(root);
	}
}
